// pages/sport/sport.js
var http = require('../../utils/util.js');
var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: app.globalData.CustomBar,
    sportsData: [],
    hasRecord: true,
    hasRankData: false,
    page: 1,
    pageSize: 7,
    titleTable: [
      "","","慢走 [4公里/小时] ","快走 [8公里/小时] ","慢跑 [9公里/小时] ",
      "快跑 [12公里/小时] ","","","单车[9公里/小时]","","单车[16公里/小时]",
      "单车[21公里/小时]","游泳[3公里/小时]","开车","跳绳","走步机[6公里/小时]",
      "仰卧起坐","乒乓球"
    ],
    sportRange: [
      {value: 2, title: "慢走 [4公里/小时] "},
      {value: 3, title: "快走 [8公里/小时] "},
      {value: 4, title: "慢跑 [9公里/小时] "},
      {value: 5, title: "快跑 [12公里/小时] "},
      {value: 8, title: "单车[9公里/小时] "},
      {value: 10, title: "单车[16公里/小时] "},
      {value: 11, title: "单车[21公里/小时] "},
      {value: 12, title: "游泳[3公里/小时] "},
      {value: 13, title: "开车 "},
      {value: 14, title: "跳绳 "},
      {value: 15, title: "走步机[6公里/小时] "},
      {value: 16, title: "仰卧起坐 "},
      {value: 17, title: "乒乓球 "},
    ],
    index: -1,
    typeValue: null,
    date: '',
    saveLoading: false,
    timeSpend: null,
    TabCur: 0,
    top: 0,
    isLoad: false,

    progress_txt: '正在加载...',
    count: 0, // 设置 计数器 初始为0
    countTimer: null, // 设置 定时器 初始为null
    step:0,
 //当前步数
  },

  
  onReady: function () {
    this.drawProgressbg();
    this.drawCircle(2);
    this.countInterval();
    let that = this;
    wx.createSelectorQuery().select('.indexes').boundingClientRect(function(res) {
      that.setData({
        barTop: res.top
      })
    }).exec()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getSportListPage(this.data.page, this.data.pageSize);
    this.tempData();
  },

  /**
   * 自动左移右移动画
   */
  autoMove() {
    setTimeout(() => {
      this.setData({
        modalName: "move-box-0"
      })
    }, 1000)
    setTimeout(() => {
      this.setData({
        modalName: null,
        ListTouchDirection: null
      })
    }, 2000)
  },

  //设置当前日期
  setTotalDate() {
    var nowDate = new Date();
    var year = nowDate.getFullYear(), month = nowDate.getMonth() + 1, day = nowDate.getDate()
    month = month < 10 ? '0' + month : month
    day = day < 10 ? '0' + day : day
    this.setData({
      "date": `${year}-${month}-${day}`
    })
  },

  // 查询我的所有运动记录
  getSportListPage(page, limit) {
    let _self = this;
    http.httpGet('/wx/sportInfo', {
      page: page,
      limit: limit
    }, (res) => {
      console.log(res)
      // 加载完所有的运动记录
      if (!res.hasRecord && page != 1) {
        _self.setData({
          isLoad: false,
          isBottom: true
        })
        return;
      }
      let list = _self.data.sportsData.concat(res.records);
      _self.setData({
        sportsData: list,
        hasRecord: res.hasRecord,
        isLoad: false,
      })
      _self.autoMove();
    })
  },

  // 添加新的记录
  saveNewSport() {
    let _self = this
    this.setData({
      saveLoading: true
    })
    let params = {
      id: this.data.id,
      dateTime: this.data.date,
      item: this.data.typeValue,
      duration: this.data.timeSpend,
      calNum: null
    }
    if (params.item != null && params.duration != null) {
      http.httpPost('/wx/sportAddReq', params, (res) => {
        params.calNum = res.round;
        let nowData = _self.data.sportsData
        // console.log(nowData)
        if (res.opType) {
          // 是添加行为
          nowData.unshift(params)
          this.setData({
            saveLoading: false,
            sportsData: nowData
          })
        } else {
          // 是更新行为
          let arrIndex = _self.getIndex1(params.id, nowData);
          nowData[arrIndex] = params
          _self.setData({
            sportsData: nowData
          })
        }
        _self.hideModal()
        wx.showToast({
          title: '操作成功!',
          icon: 'none',
          duration: 1500,
          mask:true
        })
      })
    } else {
      this.setData({
        saveLoading: false
      })
      wx.showModal({
        content: '运动项目和运动时长不能为空！',
        showCancel: false,
      })
    }
  },

  //编辑当前运动数据
  editSport(e) {
    var current = e.currentTarget.dataset.edit;
    let i = this.getIndex(current.item);
    this.setData({
      date: current.recordDate.substring(0,10),
      timeSpend: current.duration,
      index: i,
      typeValue: current.item,
      addRecord: true,
      id: current.id,
    })
  },
  // 删除当前数据
  delSport(e) {
    let _self = this;
    wx.showModal({
      title: '警告',
      content: '确认要删除吗？',
      success: function(res) {
        if (res.confirm) {
          var id = e.currentTarget.dataset.del;
          http.httpGet('/wx/delSportInfo/'+ id, {}, (res) => {
            if(res.state == 1) {
              let arr = _self.data.sportsData;
              let i = _self.getIndex1(id, arr);
              arr.splice(i, 1);
              _self.setData({
                sportsData: arr
              })
              wx.showToast({
                title: '删除成功',
                icon: 'none',
                duration: 1500,
                mask:true
              })
            } else {
              wx.showToast({
                title: '服务器忙',
                icon: 'none',
                duration: 1500,
                mask:true
              })
            }
          })
          
        }
      }
    })
  },

  getIndex(item) {
    let range = this.data.sportRange;
    for (let i = 0; i < range.length; i++) {
      if (range[i].value === item) {
        return i;
      }
    }
  },
  // 返回sportsData的索引
  getIndex1(id, arr) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].id === id) {
        return i;
      }
    }
  },
  tabSelect(e) {
    const no = e.currentTarget.dataset.id;
    this.setData({
      TabCur: no,
    })
  },
  // 滚动条事件
  onPageScroll: function(e) {
  },

  moreData() {
    this.setData({
      isLoad: true
    })
    this.data.page++;
    let limit = this.data.pageSize
    this.getSportListPage(this.data.page, limit)
  },
  
  //排行榜
  tempData: function () {
    let _self = this;  
    let urlBase = app.globalData.urlBase
    wx.request({
      url: urlBase + '/wx/sportRank',
      method: 'GET',
      success(res) {
        // console.log(res.data)
        if (res.data.length != 0) {
          _self.setData({
            list: res.data,
            hasRankData: true
          });
        }
      }
    })
  },


  drawProgressbg: function () {
    // 使用 wx.createContext 获取绘图上下文 context
    var ctx = wx.createCanvasContext('canvasProgressbg')
    ctx.setLineWidth(10);// 设置圆环的宽度
    ctx.setStrokeStyle('#686868'); // 设置圆环的颜色
    ctx.setLineCap('round') // 设置圆环端点的形状
    ctx.beginPath();//开始一个新的路径
    ctx.arc(110, 110, 100, 0.75 * Math.PI, 0.25 * Math.PI, false);
    //设置一个原点(100,100)，半径为90的圆的路径到当前路径
    ctx.stroke();//对当前路径进行描边
    ctx.draw();
  },

  drawCircle: function (step) {
    var context = wx.createCanvasContext('canvasProgress');
    // 设置渐变
    var gradient = context.createLinearGradient(200, 100, 100, 200);
    gradient.addColorStop("0", "#7acd86");
    gradient.addColorStop("0.25", "#7acd86");
    gradient.addColorStop("0.75", "#ffb300");
    gradient.addColorStop("1", "#ff4d00");

    context.setLineWidth(10);
    context.setStrokeStyle(gradient);
    context.setLineCap('round')
    context.beginPath();
    // 参数step 为绘制的圆环周长，从0到2为一周 。 -Math.PI / 2 将起始角设在12点钟位置 ，结束角 通过改变 step 的值确定
    context.arc(110, 110, 100, -1.25 * Math.PI, step * Math.PI - Math.PI * 1.25, false);
    context.stroke();
    context.draw()
  },

  
  countInterval: function () {
    let _self = this;
    http.httpGet('/wx/caloricAll', {}, (res) => {
      // console.log(res)
      let step = res.myCaloric == null ? 0 : res.myCaloric.calNum
      if (res.status == 1) {
        // 设置倒计时 定时器 每100毫秒执行一次，计数器count+1 ,耗时6秒绘一圈
        _self.countTimer = setInterval(() => {
          if (_self.data.count <= 45) {
            /* 绘制彩色圆环进度条  
            注意此处 传参 step 取值范围是0到2，
            所以 计数器 最大值 60 对应 2 做处理，计数器count=60的时候step=2
            */
           _self.drawCircle(_self.data.count / (60 / ((step > 300 ? 300 : step) / 150)))
           _self.data.count++;
          } else {
            _self.setData({
              progress_txt: step + "/300 千卡"
            });
            clearInterval(_self.countTimer);
          }
        }, 100)
      }
    })
  },

    
  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > -50 ? 'right' : 'left'
    })
  },

  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection =='left'){
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },

  
  showModal(e) {
    this.setTotalDate();
    this.setData({
      id: -1,
      timeSpend: null,
      index: -1,
      addRecord: true
    })
  },
  hideModal(e) {
    this.setData({
      addRecord: false,
      saveLoading: false
    })
  },

  PickerChange(e) {
    this.setData({
      index: e.detail.value,
      typeValue: this.data.sportRange[e.detail.value].value
    })
  },
  DateChange(e) {
    this.setData({
      date: e.detail.value
    })
  },
  DurationChange(e) {
    this.setData({
      timeSpend: e.detail.value
    })
  },
})